<template>
  <div>
    <el-row :gutter="15">
      <el-form ref="elForm" :model="dataForm" :rules="dataRule" size="medium" label-width="100px" label-position="right"
        :disabled="setting.readonly">
        <template v-if="!loading && formOperates">

          <el-col :span="24" v-if="judgeShow('billdate')">
            <el-form-item label="单据日期" prop="billdate">
              <jnpf-open-data v-model="dataForm.billdate" readonly :disabled="judgeWrite('billdate')" type="currTime">

              </jnpf-open-data>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="judgeShow('creatoruserid')">
            <el-form-item label="制单人" prop="creatoruserid">
              <jnpf-open-data v-model="dataForm.creatoruserid" readonly :disabled="judgeWrite('creatoruserid')"
                type="currUser">

              </jnpf-open-data>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="judgeShow('usedept')">
            <el-form-item label="使用部门" prop="usedept">
              <dep-select v-model="dataForm.usedept" placeholder="请选择" :disabled="judgeWrite('usedept')" clearable
                @change="changeUseDept">

              </dep-select>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="judgeShow('user')">
            <el-form-item label="使用人" prop="user">
              <user-select v-model="dataForm.user" placeholder="请选择" :disabled="judgeWrite('user')" clearable
                @change="changeUser">

              </user-select>
            </el-form-item>
          </el-col>

          <el-col :span="24" v-if="judgeShow('enclosure')">
            <el-form-item label="附件" prop="enclosure">
              <JNPF-UploadFz v-model="dataForm.enclosure" :fileSize="10" :disabled="judgeWrite('enclosure')"
                :showTip="true" sizeUnit="MB" :limit="9" buttonText="点击上传">

              </JNPF-UploadFz>
            </el-form-item>
          </el-col>
          <el-col :span="24" v-if="judgeShow('gypurapplybList') && formOperates">
            <el-form-item label-width="0">
              <div class="JNPF-common-title">
                <h2>采购申请子表</h2>
              </div>
              <el-table :data="dataForm.gypurapplybList" size='mini'>
                <el-table-column type="index" width="50" label="序号" align="center" />
                <el-table-column prop="matcode" label="物料编码" v-if="judgeShow('gypurapplybList-matcode')" width="210" >
                  <template slot="header" v-if="judgeRequired('gypurapplybList-matcode')">
                    <span class="required-sign">*</span>物料编码
                  </template>
                  <template slot-scope="scope">
                    <popupSelect v-model="scope.row.matcode" placeholder="请选择"
                      :disabled="judgeWrite('gypurapplybList') || judgeWrite('gypurapplybList-matcode')" clearable
                      :field="'matcode'+scope.$index" interfaceId="372311571319229701"
                      :columnOptions="gypurapplybmatcodecolumnOptions" propsValue="F_Id" relationField="F_MatName"
                      popupType="dialog" popupTitle="选择数据" popupWidth="800px" hasPage :pageSize="20" @change="changeMatEnclosure">
                    </popupSelect>
                  </template>
                </el-table-column>
                <el-table-column prop="" label="物料编码" width="210">
                  <template slot="header" v-if="judgeRequired('gypurapplybList-')">
                    <span class="required-sign">*</span>物料编码
                  </template>
                  <template slot-scope="scope">
                    <popupAttr :relationField="'matcode'+scope.$index" showField="F_MatCode">
                    </popupAttr>
                  </template>
                </el-table-column>
                <el-table-column prop="" label="物料规格" width="210">
                  <template slot="header" v-if="judgeRequired('gypurapplybList-')">
                    <span class="required-sign">*</span>物料规格
                  </template>
                  <template slot-scope="scope">
                    <popupAttr :relationField="'matcode'+scope.$index" showField="F_MatSpec">
                    </popupAttr>
                  </template>
                </el-table-column>
                <el-table-column prop="suppliercode" label="供应商编码" v-if="judgeShow('gypurapplybList-suppliercode')"
                  width="210">
                  <template slot="header" v-if="judgeRequired('gypurapplybList-suppliercode')">
                    <span class="required-sign">*</span>供应商编码
                  </template>
                  <template slot-scope="scope">
                    <popupSelect v-model="scope.row.suppliercode" placeholder="请选择"
                      :disabled="judgeWrite('gypurapplybList') || judgeWrite('gypurapplybList-suppliercode')" clearable
                      :field="'suppliercode'+scope.$index" interfaceId="372402284212000325"
                      :columnOptions="gypurapplybsuppliercodecolumnOptions" propsValue="F_Id" relationField="F_Code"
                      popupType="dialog" popupTitle="选择数据" popupWidth="800px" hasPage :pageSize="20" @change="changeSupplierEnclosure">
                    </popupSelect>
                  </template>
                </el-table-column>
                <el-table-column prop="" label="供应商名称" width="210">
                  <template slot="header" v-if="judgeRequired('gypurapplybList-')">
                    <span class="required-sign">*</span>供应商名称
                  </template>
                  <template slot-scope="scope">
                    <popupAttr :relationField="'suppliercode'+scope.$index" showField="F_Name">
                    </popupAttr>
                  </template>
                </el-table-column>
                <el-table-column prop="num" label="数量" v-if="judgeShow('gypurapplybList-num')" width="210">
                  <template slot="header" v-if="judgeRequired('gypurapplybList-num')">
                    <span class="required-sign">*</span>数量
                  </template>
                  <template slot-scope="scope">
                    <el-input-number v-model="scope.row.num" placeholder="数字文本"
                      :disabled="judgeWrite('gypurapplybList') || judgeWrite('gypurapplybList-num')" :step="1"
                      @change="countNum">
                    </el-input-number>
                  </template>
                </el-table-column>
                <el-table-column prop="price" label="单价" v-if="judgeShow('gypurapplybList-price')" width="210">
                  <template slot="header" v-if="judgeRequired('gypurapplybList-price')">
                    <span class="required-sign">*</span>单价
                  </template>
                  <template slot-scope="scope">
                    <el-input-number v-model="scope.row.price" placeholder="数字文本"
                      :disabled="judgeWrite('gypurapplybList') || judgeWrite('gypurapplybList-price')" :step="1"
                      @change="countPrice">
                    </el-input-number>
                  </template>
                </el-table-column>
                <el-table-column prop="amount" label="金额" v-if="judgeShow('gypurapplybList-amount')" width="210">
                  <template slot="header" v-if="judgeRequired('gypurapplybList-amount')">
                    <span class="required-sign">*</span>金额
                  </template>
                  <template slot-scope="scope">
                    <el-input-number v-model="scope.row.amount" placeholder="数字文本" :disabled="true">
                    </el-input-number>
                  </template>
                </el-table-column>
                <el-table-column prop="demandtime" label="需求时间" v-if="judgeShow('gypurapplybList-demandtime')"
                  width="210">
                  <template slot="header" v-if="judgeRequired('gypurapplybList-demandtime')">
                    <span class="required-sign">*</span>需求时间
                  </template>
                  <template slot-scope="scope">
                    <el-date-picker v-model="scope.row.demandtime" placeholder="请选择"
                      :disabled="judgeWrite('gypurapplybList') || judgeWrite('gypurapplybList-demandtime')" clearable
                      :style='{"width":"100%"}' type="date" format="yyyy-MM-dd" value-format="timestamp">
                    </el-date-picker>
                  </template>
                </el-table-column>
                <el-table-column prop="usedept" label="使用部门" v-if="judgeShow('gypurapplybList-usedept')" width="210">
                  <template slot="header" v-if="judgeRequired('gypurapplybList-usedept')">
                    <span class="required-sign">*</span>使用部门
                  </template>
                  <template slot-scope="scope">
                    <dep-select v-model="scope.row.usedept" placeholder="请选择"
                      :disabled="judgeWrite('gypurapplybList') || judgeWrite('gypurapplybList-usedept')" clearable>
                    </dep-select>
                  </template>
                </el-table-column>
                <el-table-column prop="user" label="使用人" v-if="judgeShow('gypurapplybList-user')" width="210">
                  <template slot="header" v-if="judgeRequired('gypurapplybList-user')">
                    <span class="required-sign">*</span>使用人
                  </template>
                  <template slot-scope="scope">
                    <user-select v-model="scope.row.user" placeholder="请选择"
                      :disabled="judgeWrite('gypurapplybList') || judgeWrite('gypurapplybList-user')" clearable>
                    </user-select>
                  </template>
                </el-table-column>
                <el-table-column prop="plannumid" label="计划号主键" v-if="judgeShow('gypurapplybList-plannumid')"
                  width="210">
                  <template slot="header" v-if="judgeRequired('gypurapplybList-plannumid')">
                    <span class="required-sign">*</span>计划号主键
                  </template>
                  <template slot-scope="scope">
                    <popupSelect v-model="scope.row.plannumid" placeholder="请选择"
                      :disabled="judgeWrite('gypurapplybList') || judgeWrite('gypurapplybList-plannumid')" clearable
                      :field="'plannumid'+scope.$index" interfaceId="372747358020050245"
                      :columnOptions="gypurapplybplannumidcolumnOptions" propsValue="F_Id" relationField="F_PlanCode"
                      popupType="dialog" popupTitle="选择数据" popupWidth="800px">
                    </popupSelect>
                  </template>
                </el-table-column>
                <el-table-column prop="matenclosure" label="物料附件" v-if="judgeShow('gypurapplybList-matenclosure')"
                  width="210">
                  <template slot="header" v-if="judgeRequired('gypurapplybList-matenclosure')">
                    <span class="required-sign">*</span>物料附件
                  </template>
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.matenclosure" placeholder="请输入"
                      :disabled="judgeWrite('gypurapplybList') || judgeWrite('gypurapplybList-matenclosure')" clearable
                      :style='{"width":"100%"}'>
                    </el-input>
                  </template>
                </el-table-column>
                <el-table-column prop="supplierenclosure" label="供应商附件"
                  v-if="judgeShow('gypurapplybList-supplierenclosure')" width="210">
                  <template slot="header" v-if="judgeRequired('gypurapplybList-supplierenclosure')">
                    <span class="required-sign">*</span>供应商附件
                  </template>
                  <template slot-scope="scope">
                    <el-input v-model="scope.row.supplierenclosure" placeholder="请输入"
                      :disabled="judgeWrite('gypurapplybList') || judgeWrite('gypurapplybList-supplierenclosure')"
                      clearable :style='{"width":"100%"}'>
                    </el-input>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="50" v-if="!setting.readonly && !judgeWrite('gypurapplybList')">
                  <template slot-scope="scope">
                    <el-button size="mini" type="text" class="JNPF-table-delBtn"
                      @click="delgypurapplybList(scope.$index)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <div class="table-actions" @click="addgypurapplybList()">
                <el-button type="text" icon="el-icon-plus">添加</el-button>
              </div>
            </el-form-item>
          </el-col>
        </template>
      </el-form>
    </el-row>
    <UserBox v-if="userBoxVisible" ref="userBox" @submit="submit" />
  </div>
</template>
<script>
  import request from '@/utils/request'
  import {
    getDataInterfaceRes
  } from '@/api/systemData/dataInterface'
  import {
    getDictionaryDataSelector
  } from '@/api/systemData/dictionary'
  export default {
    components: {},
    props: [],
    data() {
      return {
        visible: false,
        loading: false,
        setting: {},
        eventType: '',
        userBoxVisible: false,
        currTableConf: {},
        addTableConf: {
          gypurapplybList: {
            "popupType": "dialog",
            "hasPage": true,
            "popupTitle": "选择数据",
            "pageSize": 20,
            "columnOptions": [],
            "interfaceId": "",
            "interfaceName": "",
            "relationOptions": [],
            "templateJson": [],
            "popupWidth": "800px"
          },
        },
        tableRows: {
          gypurapplybList: {
            matcode: '',
            suppliercode: '',
            num: '',
            price: '',
            amount: '',
            demandtime: '',
            plannumid: '',
            matenclosure: '',
            supplierenclosure: '',
            enabledmark: undefined
          }
        },
        dataForm: {
          id: '',
          flowId: '',
          status: 1,
          freeapproveruserid: '',
          flowUrgent: 1,
          billcode: undefined,
          billdate: undefined,
          creatoruserid: undefined,
          usedept: undefined,
          user: undefined,
          approvestatus: undefined,
          approvetime: undefined,
          approveuser: undefined,
          enclosure: [],
          applydept: undefined,
          lastmodifyuserid: undefined,
          lastmodifytime: undefined,
          gypurapplybList: [],
        },
        tableRequiredData: {},
        dataRule: {
          usedept: [{
            required: true,
            message: '请选择',
            trigger: 'change'
          }, ],
          user: [{
            required: true,
            message: '请选择',
            trigger: 'click'
          }, ],



          matcode: [{
            required: true,
            message: '请至少选择一个',
            trigger: 'change'
          }, ],
          suppliercode: [{
            required: true,
            message: '请至少选择一个',
            trigger: 'change'
          }, ],
          num: [{
            required: true,
            message: '请至少选择一个',
            trigger: ["blur", "change"]
          }, ],
          price: [{
            required: true,
            message: '数字文本',
            trigger: ["blur", "change"]
          }, ],
          demandtime: [{
            required: true,
            message: '请选择',
            trigger: 'change'
          }, ],
          usedept: [{
            required: true,
            message: '请选择',
            trigger: 'change'
          }, ],
          user: [{
            required: true,
            message: '请选择',
            trigger: 'click'
          }, ],
          plannumid: [{
            required: true,
            message: '请选择',
            trigger: 'change'
          }, ],

        },

        gypurapplybmatcodecolumnOptions: [{
          "label": "物料编码",
          "value": "F_MatCode"
        }, {
          "label": "物料名称",
          "value": "F_MatName"
        }, {
          "label": "物料规格",
          "value": "F_MatSpec"
        },

        ],
        gypurapplybsuppliercodecolumnOptions: [{
          "label": "供应商编码",
          "value": "F_Code"
        }, {
          "label": "供应商名称",
          "value": "F_Name"
        }, ],
        gypurapplybplannumidcolumnOptions: [{
          "label": "计划号",
          "value": "F_PlanCode"
        }, {
          "label": "主键",
          "value": "F_Id"
        },

        ],
      }
    },
    computed: {
      formOperates() {
        return this.setting.formOperates
      }
    },
    watch: {},
    created() {},
    mounted() {},
    methods: {
      changeSupplierEnclosure(value, valueData){
        if (value === undefined || value === '') {
          return
        }
        for (let i = 0; i < this.dataForm.gypurapplybList.length; i++) {
          console.log(valueData)
          this.dataForm.gypurapplybList[i].supplierenclosure=valueData.F_Attachment

        }
      },
      changeMatEnclosure(value, valueData){
        if (value === undefined || value === '') {
          return
        }
        for (let i = 0; i < this.dataForm.gypurapplybList.length; i++) {
          this.dataForm.gypurapplybList[i].matenclosure=valueData.F_Enclosure

        }
      },
      countNum(value, valueData) {

        if (value === undefined || value === '') {
          return
        }
        for (let i = 0; i < this.dataForm.gypurapplybList.length; i++) {

          this.dataForm.gypurapplybList[i].amount = this.dataForm.gypurapplybList[i].num * this.dataForm
            .gypurapplybList[i].price
        }
      },
      countPrice(value, valueData) {

        if (value === undefined || value === '') {
          return
        }
        for (let i = 0; i < this.dataForm.gypurapplybList.length; i++) {


          this.dataForm.gypurapplybList[i].amount = this.dataForm.gypurapplybList[i].num * this.dataForm
            .gypurapplybList[i].price
        }
      },
      changeUser(value, valueData) {
        if (value === undefined || value === '') {
          return
        }
        for (let i = 0; i < this.dataForm.gypurapplybList.length; i++) {
          this.dataForm.gypurapplybList[i].user = value
        }
      },
      changeUseDept(value, valueData) {
        console.log(value)
        if (value === undefined || value === '') {
          return
        }
        for (let i = 0; i < this.dataForm.gypurapplybList.length; i++) {
          this.dataForm.gypurapplybList[i].usedept = value
        }
      },

      judgeShow(id) {
        if (!this.setting.formOperates || !this.setting.formOperates.length) return true
        let arr = this.setting.formOperates.filter(o => o.id === id) || []
        if (!arr.length) return true
        let item = arr[0]
        return item.read
      },
      judgeWrite(id) {
        if (!this.setting.formOperates || !this.setting.formOperates.length) return false
        let arr = this.setting.formOperates.filter(o => o.id === id) || []
        if (!arr.length) return true
        let item = arr[0]
        return !item.write
      },
      goBack() {
        this.$emit('refresh')
      },
      init(data) {
        this.dataForm.id = data.id || "";
        this.setting = data;
        this.visible = true;
        this.updateDataRule()
        this.$nextTick(() => {
          this.$refs['elForm'].resetFields();
          if (this.dataForm.id) {
            this.loading = true
            request({
              url: '/api/example/GyPurApply/' + this.dataForm.id,
              method: 'get'
            }).then(res => {
              this.dataInfo(res.data)
              this.loading = false
            })
          }
          this.$emit('setPageLoad')
        })
        this.$store.commit('generator/UPDATE_RELATION_DATA', {})
      },
      updateDataRule() {
        let newRules = {}
        for (let i = 0; i < this.setting.formOperates.length; i++) {
          const item = this.setting.formOperates[i]
          if (!item.id.includes('-')) {
            const newRulesItem = {
              required: item.required,
              message: item.name + '不能为空',
              trigger: item.trigger || 'blur'
            }
            if (!this.dataRule.hasOwnProperty(item.id)) {
              if (item.required) this.$set(newRules, item.id, [newRulesItem])
            } else {
              let withoutRequiredItem = true
              for (let i = 0; i < this.dataRule[item.id].length; i++) {
                if (this.dataRule[item.id][i].hasOwnProperty('required')) {
                  this.dataRule[item.id][i].required = item.required
                  withoutRequiredItem = false
                }
              }
              if (withoutRequiredItem && item.required) this.dataRule[item.id].push(newRulesItem)
            }
          } else {
            let key = item.id.split('-')[0]
            let newId = item.id.split('-')[1]
            let newItem = {
              ...item,
              id: newId
            }
            if (!this.tableRequiredData.hasOwnProperty(key)) {
              this.$set(this.tableRequiredData, key, [newItem])
            } else {
              this.tableRequiredData[key].push(newItem)
            }
          }
        }
        this.dataRule = {
          ...this.dataRule,
          ...newRules
        }
      },
      exist() {
        let isOk = true
        for (let key in this.tableRequiredData) {
          if (this.dataForm[key] && Array.isArray(this.dataForm[key])) {
            for (let i = 0; i < this.dataForm[key].length; i++) {
              let item = this.dataForm[key][i]
              inner: for (let id in item) {
                let arr = this.tableRequiredData[key].filter(o => o.id === id) || []
                if (!arr.length) continue inner
                if (arr[0].required) {
                  let msg = `${arr[0].name}不能为空`
                  let boo = true
                  if (arr[0].dataType === 'array') {
                    boo = !this.jnpf.isEmptyArray(item[id])
                  } else {
                    boo = !this.jnpf.isEmpty(item[id])
                  }
                  if (!boo) {
                    this.$message({
                      message: msg,
                      type: 'error',
                      duration: 1000
                    })
                    isOk = false
                    break
                  }
                }
              }
            }
          }
        }
        return isOk
      },
      judgeRequired(id) {
        if (!this.formOperates || !this.formOperates.length) return false
        let arr = this.formOperates.filter(o => o.id === id) || []
        if (!arr.length) return false
        let item = arr[0]
        return item.required
      },
      // 表单提交
      dataFormSubmit(eventType, flowUrgent) {
      if(this.dataForm.user===undefined||this.dataForm.user===''){
         this.$message.error('使用人不能为空');
         return
      }
      if(this.dataForm.usedept===undefined||this.dataForm.usedept===''){
         this.$message.error('使用部门不能为空');
         return
      }
        this.$refs['elForm'].validate((valid) => {
          if (valid) {
            if (this.exist && !this.exist()) return
            if (eventType === 'audit' || eventType === 'reject') {
              this.$emit('eventReceiver', this.dataForm, eventType)
              return
            }
            this.dataForm.status = eventType === 'submit' ? 0 : 1
            this.dataForm.flowId = this.setting.flowId
            this.dataForm.flowUrgent = flowUrgent
            this.eventType = eventType
            if (this.eventType === 'submit') {
              this.$confirm('您确定要提交当前流程吗, 是否继续?', '提示', {
                type: 'warning'
              }).then(() => {
                this.request()
              }).catch(() => {});
            } else {
              this.request()
            }
          }
        })
      },
      request() {
        var _data = this.dataList()
        if (!this.dataForm.id) {
          request({
            url: '/api/example/GyPurApply',
            method: 'post',
            data: _data
          }).then((res) => {
            this.$message({
              message: res.msg,
              type: 'success',
              duration: 1000,
              onClose: () => {
                this.visible = false
                this.$emit('close', true)
              }
            })
          })
        } else {
          request({
            url: '/api/example/GyPurApply/' + this.dataForm.id,
            method: 'PUT',
            data: _data
          }).then((res) => {
            this.$message({
              message: res.msg,
              type: 'success',
              duration: 1000,
              onClose: () => {
                this.visible = false
                this.$emit('close', true)
              }
            })
          })
        }
      },
      addgypurapplybList() {
        let item = {
          matcode: undefined,
          suppliercode: undefined,
          num: undefined,
          price: undefined,
          amount: undefined,
          demandtime: undefined,
          usedept: undefined,
          user: undefined,
          plannumid: undefined,
          matenclosure: undefined,
          supplierenclosure: undefined,
        }
        this.dataForm.gypurapplybList.push(item)
        /**
         * 新增子表时字段带入主表使用人、使用部门
         */
        if (this.dataForm.user != undefined || this.dataForm.user != '' || this.dataForm.usedept != undefined || this
          .dataForm.usedept != '') {

          for (let i = 0; i < this.dataForm.gypurapplybList.length; i++) {
            this.dataForm.gypurapplybList[i].user = this.dataForm.user
            this.dataForm.gypurapplybList[i].usedept = this.dataForm.usedept
          }
        }

      },
      delgypurapplybList(index) {
        this.dataForm.gypurapplybList.splice(index, 1);
      },
      openSelectDialog(key) {
        this.currTableConf = this.addTableConf[key]
        this.currVmodel = key
        this.selectDialogVisible = true
        this.$nextTick(() => {
          this.$refs.selectDialog.init()
        })
      },
      addForSelect(data) {
        for (let i = 0; i < data.length; i++) {
          let item = {
            ...this.tableRows[this.currVmodel],
            ...data[i]
          }
          this.dataForm[this.currVmodel].push(item)
        }
      },
      dataList() {
        var _data = JSON.parse(JSON.stringify(this.dataForm));








        _data.enclosure = JSON.stringify(_data.enclosure)




        for (let i = 0; i < _data.gypurapplybList.length; i++) {
          var _list = _data.gypurapplybList[i];
        }
        return _data;
      },
      dataInfo(dataAll) {
        let _dataAll = dataAll
        _dataAll.enclosure = JSON.parse(_dataAll.enclosure)
        for (let i = 0; i < _dataAll.gypurapplybList.length; i++) {
          var _list = _dataAll.gypurapplybList[i];
        }
        this.dataForm = _dataAll
      },
    },
  }
</script>
